package org.mjl.jackson.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * TdtMapUtil
 *
 * @author mjl
 * @date 2021-04-12
 */
public class TdtMapUtil {

    /**
     * 天地图TK，此处需使用服务器端TK
     * 使用浏览器端TK会提示：403 Forbidden: "{"msg":"权限类型错误","resolve":"Key权限类型为:浏览器端，请使用浏览器端访问！","code":12}"
     */
    private static final String TDT_MAP_TK = "ea62f066c2db1f0b4368429ef4ad92d1";
    // 服务端TK
//    private static final String TDT_MAP_TK = "42cac2e93c11cb94a8d5c81025ddb0db";

    /**
     * 输入地址返回经纬度
     * 接口说明网址 http://lbs.tianditu.gov.cn/server/geocodinginterface.html
     */
    private static final String TDT_MAP_GEO_API = "http://api.tianditu.gov.cn/geocoder";

    private static ObjectMapper objectMapper = new ObjectMapper();

    public TdtMapUtil() {
    }

    public static Map<String, String> getLonlat(String address) {
        Map<String, String> resultMap = new HashMap<>();

        try {
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("keyWord", address);
            String paramsJson = objectMapper.writeValueAsString(paramsMap);
            String url = TDT_MAP_GEO_API + "?ds={ds}&tk=" + TDT_MAP_TK;
            System.out.println(url);
            RestTemplate restTemplate = new RestTemplate();

            String object = restTemplate.getForObject(url, String.class, paramsJson);
            Map map = objectMapper.readValue(object, Map.class);
            String status = String.valueOf(map.get("status"));
            if ("0".equals(status)) {
                Map<String, Object> location = (Map<String, Object>) map.get("location");
                String lng = String.valueOf(location.get("lon"));
                String lat = String.valueOf(location.get("lat"));
                resultMap.put("lon", lng);
                resultMap.put("lat", lat);
                resultMap.put("lonlat", lng + "," + lat);
            }
            resultMap.put("msg", statusCode(status));
            return resultMap;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // TODO:
    private static String statusCode(String status) {
        String msg = "正常";
        switch (status) {
            case "0":
                msg = "正常";
                break;
            case "1":
                msg = "服务器内部错误";
                break;
            case "2":
                msg = "请求参数非法，必要参数拼写错误或漏传（如query和tag请求中均未传入）";
                break;
            case "3":
                msg = "权限校验失败";
                break;
            case "4":
                msg = "配额校验失败，服务当日调用次数已超限，请前往API控制台提升";
                break;
            case "5":
                msg = "ak不存在或者非法\t(未传入ak参数；ak已被删除（可前往回收站恢复）)";
                break;
            case "101":
                msg = "服务禁用(请到控制台检验您的AK是否有该服务权限)";
                break;
            case "102":
                msg = "不通过白名单或者安全码不对";
                break;
            case "2xx":
                msg = "无权限";
                break;
            case "3xx":
                msg = "配额错误";
                break;
        }
        return msg;
    }

    public static void main(String[] args) {
//        System.out.println(getLonlat("甘肃省兰州市天庆嘉园"));
        System.out.println(getLonlat("北京市海淀区彩和坊路海淀西大街74号"));
    }
}
